Skip to content

Conversation

@pguyot
Copy link
Collaborator

@pguyot pguyot commented Nov 2, 2025

See #1953

These changes are made under both the "Apache 2.0" and the "GNU Lesser General
Public License 2.1 or later" license terms (dual license).

SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later

@pguyot pguyot force-pushed the w44/lists-flatten-as-nif branch 2 times, most recently from 005cf1e to d623db2 Compare November 3, 2025 07:21
if (term_is_nonempty_list(t)) {
term t_head = term_get_list_head(t);
term t_tail = term_get_list_tail(t);
if (term_is_nonempty_list(t_tail)) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks good, but my guess is that it can be replaced with a slightly optimized alternative implementation that doesn't push all values, but only when there are nested lists.

This should optimize the trivial case (such as [1, 2, 3, 4]), by avoiding copying to the temp stack the entire list.

Basically we should push t_tail to the stack every time t_head is a term_is_nonempty_list.
In that case t_tail is used as a "continuation value" as soon as the current list is finished.

e.g.

flatten([[1, 2], 5, 6, 7]):
iteration 0:
  - t is [[1, 2], 5, 6, 7]
  - t_head is [1, 2]
  - t_tail is [5, 6, 7]
  - t_tail is pushed to the stack
  - t is set to [1, 2]
...
  when t is []:
  - t is popped from the stack
iteration n:
  - t is [5, 6, 7]
  ...

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea. I also optimized this further to reuse the longest reusable tail from original list.

NIF optimizes memory allocation by using a minimal stack to flatten,
allocating on the heap only what is required to hold the flattened list and
reusing the largest reusable tail from the original list.

Signed-off-by: Paul Guyot <[email protected]>
@pguyot pguyot force-pushed the w44/lists-flatten-as-nif branch from d623db2 to ddd8071 Compare November 15, 2025 21:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants